package com.qf.limit.controller;

import com.qf.limit.commons.r.Codes;
import com.qf.limit.commons.r.R;
import com.qf.limit.commons.utils.CodesUtils;
import com.qf.limit.commons.utils.EmailUtils;
import com.qf.limit.entity.User;
import com.qf.limit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

@RestController
@RequestMapping("/email")
@Validated
public class EmailController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmailUtils emailUtils;

    @RequestMapping("/sendCode")
    public R sendCode(@NotBlank(message = "用户名不能为空") String username){
        //根据用户获取用户的邮箱
        User user = userService.queryUserName(username);
        if (user == null){
            return R.fail(Codes.USER_NOT_FOUND);
        }
        //用户存在
        String email = user.getEmail();
        //生成验证码[0,1),0.1
        int codes = (int) (Math.random()*9000+1000);
        //发送邮件
        emailUtils.sendEmailCode(email,codes);
        //将验证码到Map集合中
        CodesUtils.putCode(username,codes);
        //返回给前端的邮箱地址需要隐藏部分
        String content = email.substring(3,email.lastIndexOf("@"));
        email = email.replace(content,"********");
        return R.succ(email);
    }
}
